package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.DeviceDataPageReqDto;
import com.zzyl.serve.listener.IotMsgNotifyData;
import com.zzyl.serve.listener.IotMsgService;
import com.zzyl.serve.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设备数据Service业务层处理
 *
 * @author wangyc
 * @date 2025-08-23
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        LambdaQueryWrapper<DeviceData> wrapper = Wrappers.<DeviceData>lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .like(ObjectUtils.isNotEmpty(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime);
        //使用iService继承的page分页方法来实现查询列表数据
        Page<DeviceData> page = page(Page.of(dto.getPageNum(), dto.getPageSize()), wrapper);
        TableDataInfo<DeviceData> dataInfo = new TableDataInfo<>();
        dataInfo.setMsg("查询成功");
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setTotal(page.getTotal());
        dataInfo.setRows(page.getRecords());
        return dataInfo;
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    @Override
    public void batchSaveDeviceData(IotMsgNotifyData iotMsgNotifyData) {

        //根据设备id查询 去设备表中查询，判断是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId);
        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            log.error("上报数据，设备id不存在,deviceid{}", deviceId);
            return;
        }
        //创建一个集合来批量存储物模型数据
        List<DeviceData> dataList = new ArrayList<>();
        IotMsgService iotMsgService = iotMsgNotifyData.getBody().getServices().get(0);
        String eventTimeStr = iotMsgService.getEventTime();
        LocalDateTime eventTime1 = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        //一行代码，将eventTime1 0时区转换为东八区时区
        LocalDateTime eventTime = eventTime1.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        //获取设备的所有物模型
        Map<String, Object> properties = iotMsgService.getProperties();
        if (ObjectUtils.isEmpty(properties)) {
            return;
        }
        properties.forEach((prop, value) ->
        {
            DeviceData deviceData = new DeviceData();
            deviceData.setFunctionId(prop);
            deviceData.setDataValue(value.toString());
            deviceData.setAlarmTime(eventTime);
            deviceData.setIotId(deviceId);
            deviceData.setDeviceName(device.getDeviceName());
            deviceData.setProductKey(device.getProductKey());
            deviceData.setProductName(device.getProductName());
            deviceData.setAccessLocation(device.getBindingLocation());
            deviceData.setLocationType(device.getLocationType());
            deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
            dataList.add(deviceData);
        });
        System.out.println("开始批量保存");
        saveBatch(dataList);
        //将最新的设备数据，存放到redis缓存中
        redisTemplate.opsForHash().put(CacheConstants.DEVICE_DATA_ALL_LAST,deviceId, JSONUtil.toJsonStr(dataList));

    }
}
